
    var xhr;
    var timerId;
    
	function addActivity(jsonMsg){
		
        var activity = eval('(' + jsonMsg + ')');
                
        var activityNode = $("<div class='activity'> </div>");
        
        var titleNode = $("<div class='title'> </div>");
        var titleAnchor = $("<a href='" + activity.source + "' target='_blank' >" + activity.title + "</a>");
        titleNode.append(titleAnchor);
        
        var contentNode = $("<div>"+ activity.content +"</div>");
        
        activityNode.append(titleNode);
        activityNode.append(contentNode);
        
        activityNode.hide();
        
        $("#messages").prepend(activityNode);
        
        activityNode.slideDown("fast");
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
      xhr = $.ajax({
            type: "GET",
            url: "getupdates",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:30000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                if(data != 'Q_EMPTY')
                	addActivity(data); /* Add response to a .msg div (with the "new" class)*/
                    timerId = setTimeout(
                                'waitForMsg()', /* Request next message */
                                1000 /* ..after 1 second */
                             );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addActivity(textStatus + " (" + errorThrown + ")");
                setTimeout(
                    'waitForMsg()', /* Try again after.. */
                    "15000"); /* milliseconds (15seconds) */
            },
        });
    };

    function toggleStream() {
    	var pause = "Pause Updates";
    	var resume = "Resume Updates";
    	
    	var curState = $("#togglefeedBtn").text(); 
    	var pos = curState.indexOf(pause);
    	if (pos != -1) {
    		$("#togglefeedBtn").text(resume);
    		pauseStream();
    	}
    	else {
    		$("#togglefeedBtn").text(pause);
    		resumeStream();
    	}
    }
    
    function pauseStream() {
    	clearTimeout(timerId);
    	xhr.abort();
    }
    
    function resumeStream() {
    	waitForMsg();
    }
    
    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */

        $("#togglefeedBtn").click(function () { 
            toggleStream();
         });
    });

    
